<?php

namespace Cours\QuizzBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class UtilisateurController extends Controller {

    /**
     * @Route("/index")
     * @Template()
     */
    public function indexAction() {

        $rep = $this->getDoctrine()->getManager()->getRepository('CoursQuizzBundle:Utilisateur');

        $formBuilder = $this->createFormBuilder()
                ->add('login', 'text')
                ->add('password', 'password');

        $form = $formBuilder->getForm();
        $request = $this->get('request');

        if ($request->getMethod() == 'POST') {
            $form->bind($request);

            if ($form->isValid()) {
                $identifiant = $form['login']->getData();
                $mdp = $form['password']->getData();
                $trouve = $rep->findBy(array('login' => $identifiant, 'password' => $mdp));
                if ($trouve) {
                    $session->set('login', $identifiant);
                    $session->set('password', $mdp);
                    return $this->render('CoursQuizzBundle:Quizz:index.html.twig');
                } else {
                    return $this->render('CoursQuizzBundle:Utilisateur:index.html.twig', array('form' => $form->CreateView()));
                }
            }
        }
        return $this->render('CoursQuizzBundle:Utilisateur:index.html.twig', array('form' => $form->CreateView()));
    }

    public function deconnectionAction() {
        $session = $this->getRequest()->getSession();
        $session->invalidate();

        return $this->redirect($this->generateUrl('auth'));
    }

}
